package by.alex.dzeshko.lastfmsimple.app.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import by.alex.dzeshko.lastfmsimple.R;
import by.alex.dzeshko.lastfmsimple.adapter.TracksCursorAdapter;
import by.alex.dzeshko.lastfmsimple.api.LastFmApi;
import by.alex.dzeshko.lastfmsimple.app.activity.DetailActivity;
import by.alex.dzeshko.lastfmsimple.app.activity.MainActivity;
import by.alex.dzeshko.lastfmsimple.appstate.AppState.ScreenState;
import by.alex.dzeshko.lastfmsimple.content.Contract;
import by.alex.dzeshko.lastfmsimple.images.ImageLoader;
import by.alex.dzeshko.lastfmsimple.service.InfoService;
import by.alex.dzeshko.lastfmsimple.service.common.CommonService;

import com.actionbarsherlock.app.SherlockFragment;

/**
 * A fragment representing a single Albums detail screen. This fragment is
 * either contained in a {@link MainActivity} in two-pane mode (on tablets) or a
 * {@link DetailActivity} on handsets.
 */
public class AlbumsDetailFragment extends SherlockFragment implements
		LoaderCallbacks<Cursor> {

	private static String[] PROJECTION = new String[] {
			Contract.TracksColumns.ARTIST, Contract.TracksColumns.NAME,
			Contract.TracksColumns.MARKER, Contract.TracksColumns.MBID };

	private ListView mTracksListView;

	private ImageView mCoverImageView;

	private ProgressBar mProgressBar;

	private TracksCursorAdapter mCursorAdapter;

	private String mCoverUrl, mTableMarker;

	private BroadcastReceiver mBroadcastReceiver;

	public static final String ALBUM_MBID = "ALBUM_MBID";

	public static final String ALBUM_COVER = "COVER";

	private static final String LOG_TAG = "AlbumsDetailFragment";

	public AlbumsDetailFragment() {
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//setRetainInstance(true);
		Bundle args = getArguments();
		mCoverUrl = args.getString(DetailActivity.COVER);
		mTableMarker = args.getString(DetailActivity.MARKER);
		Intent info = new Intent(getSherlockActivity(), InfoService.class);
		if (args.containsKey(DetailActivity.MBID)) {
			String mbid = args.getString(DetailActivity.MBID);
			args.putString(InfoService.URL, LastFmApi.getAlbumInfo(mbid));
			info.putExtra(DetailActivity.ARGUMENTS, args);
			getSherlockActivity().startService(info);
		} else if(args.containsKey(DetailActivity.ARTIST) && args.containsKey(DetailActivity.ALBUM)) {
			String artist = args.getString(DetailActivity.ARTIST);
			String album = args.getString(DetailActivity.ALBUM);
			args.putString(InfoService.URL, LastFmApi.getAlbumInfo(artist, album));
			info.putExtra(DetailActivity.ARGUMENTS, args);
			getSherlockActivity().startService(info);
		}
		mCursorAdapter = new TracksCursorAdapter(getSherlockActivity(), null);
		mCursorAdapter.setImagesPresence(false);
		mBroadcastReceiver = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {
				String action = intent.getAction();
				if (action.equals(InfoService.ACTION_ON_ERROR)) {
					mProgressBar.setVisibility(View.GONE);
					Toast.makeText(
							getSherlockActivity(),
							intent.getStringExtra(CommonService.EXTRA_KEY_MESSAGE),
							Toast.LENGTH_SHORT).show();
				} else if (action.equals(InfoService.ACTION_ON_SUCCESS)) {
					mProgressBar.setVisibility(View.GONE);
				}
			}
		};
		IntentFilter filter = new IntentFilter();
		filter.addAction(InfoService.ACTION_ON_ERROR);
		filter.addAction(InfoService.ACTION_ON_SUCCESS);
		getSherlockActivity().registerReceiver(mBroadcastReceiver, filter);
		getSherlockActivity().getSupportLoaderManager().initLoader(3, null,
				this);
	}

	@Override
	public void onDestroy() {
		Log.d(LOG_TAG, "onDestroy");
		
		getSherlockActivity().unregisterReceiver(mBroadcastReceiver);
		super.onDestroy();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		Log.d(LOG_TAG, "onCreate");
		View rootView = inflater.inflate(R.layout.fragment_albums_detail, null);
		mTracksListView = (ListView) rootView
				.findViewById(R.id.listview_fragment_albumdetails);
		mCoverImageView = (ImageView) rootView
				.findViewById(R.id.view_fragment_albumsdetails_background);
		mProgressBar = (ProgressBar) rootView
				.findViewById(R.id.progressbar_fragment_albumdetails);
		ImageLoader.getInstance().bind(mCoverImageView, mCoverUrl);
		mTracksListView.setAdapter(mCursorAdapter);
		return rootView;
	}

	@Override
	public Loader<Cursor> onCreateLoader(int arg0, Bundle bundle) {
		Log.d(LOG_TAG, "onCreateLoader");
		return new CursorLoader(getSherlockActivity(),
				Contract.TracksColumns.CONTENT_URI, PROJECTION,// null, null, null);
				Contract.TracksColumns.MARKER + " = ?",
				new String[] { mTableMarker }, null);
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
		mCursorAdapter.swapCursor(cursor);
	}

	@Override
	public void onLoaderReset(Loader<Cursor> loader) {
		mCursorAdapter.swapCursor(null);
	}
	
}
